package cn.yunyichina.provider.pay.alipay.service.impl;

import cn.yunyichina.provider.framework.qiniu.QiniuService;
import cn.yunyichina.provider.framework.utils.HttpUtils;
import cn.yunyichina.provider.framework.utils.ZipUtils;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.pay.alipay.config.Alipay;
import cn.yunyichina.provider.pay.alipay.config.Config;
import cn.yunyichina.provider.pay.alipay.service.AlipayDownloadService;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;
import java.util.Properties;

/**
 * 下载官方对账文件
 * Created by JoeZ on 2016/10/14.
 */
@Service
public class AlipayDownloadServiceImpl implements AlipayDownloadService {

    private static final Logger logger = LoggerFactory.getLogger(AlipayDownloadServiceImpl.class);

    @Resource
    private Properties yaml;

    private String resultCode = "";
    private String resultMessage = "";

    /**
     * 获取本地对账文件路径
     * @return
     */
    @Override
    public Response getAlipayDownloadBillFile(String json) {

        Map<String , String> map = JSON.parseObject(json, Map.class);
        String date = map.get("date");
        String appId = map.get("appId");
        String publicKey = map.get("publicKey");
        String privateKey = map.get("privateKey");
        String orgName = map.get("orgName");
        String url = getAlipayDownloadBill(date,appId,publicKey,privateKey);
        Response response = new Response();
        response.setResultCodeAndMessage(resultCode , resultMessage);

        if(StringUtils.isNotBlank(url)){
            String fileName = url.substring(url.indexOf("bizDates=") + 9, url.indexOf("bizDates=") + 17);
            try {
                String outPutPath = yaml.getProperty(Alipay.ALI_PAY_CHECK_ACCOUNT_SAVE_FILE_PATH);
                String alipayFileName = orgName +"_alipay_" + fileName + "_" + appId +".csv";
                fileName = URLDecoder.decode(outPutPath + orgName +"_alipay_" + fileName +"_"+ appId +".zip","UTF-8");
                logger.info(">>> OutPutPath:" + outPutPath);
                logger.info(">>> FileName:" + fileName);
                boolean type = HttpUtils.httpDownload(url, fileName);
                if(type){
                    com.qiniu.http.Response res = QiniuService.upload(ZipUtils.unZipFiles(fileName, outPutPath, alipayFileName), alipayFileName, Config.QINIU_BUCKET_FOR_CHECKACCOUNT);
                    if(res.isOK() || res.statusCode == 614){
                        response.setResult(alipayFileName);
                        response.setResultCodeAndMessage("0","本地文件获取成功");
                    }else{
                        logger.info("check_account_file_qiniu_download_fail!!");
                        response.setResultCodeAndMessage("11001","失败");
                    }
                }else{
                    logger.info("check_account_file_httpDownload_fail!!");
                }
            } catch (UnsupportedEncodingException e) {
                logger.error("[AlipayDownloadServiceImpl.getAlipayDownloadBillFile]" , e);
            }
        }

        return response;
    }



    /**
     * 拼装请求参数
     * @param date
     * @return
     */
    @Override
    public String getAlipayDownloadBill(String date, String appId,String publicKey,String privateKey) {

        String resUrl = "";

        String url = yaml.getProperty(Alipay.ALI_PAY_BILL_DOWNLOAD_URL);

        logger.info(">>> appId:" + appId);
        logger.info(">>> url:" + url);
        logger.info(">>> privateKey:" + privateKey);
        logger.info(">>> publicKey:" + publicKey);
        logger.info("AlipayDownloadServiceImpl.getAlipayDownloadBill 公钥长度：" + publicKey.length());

        String signType = "";
        if(publicKey.length() <= 216){
            signType = "RSA";
        }else{
            signType = "RSA2";
        }

        try {
            AlipayClient alipayClient = new DefaultAlipayClient(url ,appId ,privateKey,"json","UTF-8", publicKey, signType);
            AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();
            request.setBizContent("{" +
                    "    \"bill_type\":\"trade\"," +
                    "    \"bill_date\":\""+ date +"\"" +
                    "  }");
            logger.info(">>>> alipay Json:" + JSON.toJSONString(request.getBizContent()));
            AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                logger.debug(">>>>>" + response.getMsg() + ":" + response.getSubMsg());
                resUrl = response.getBillDownloadUrl();
            } else {
                logger.debug(">>>>>获取支付宝下载链接失败：" + response.getCode() + ":" + response.getMsg() + "-----" +response.getSubCode()+":"+ response.getSubMsg());
            }
            resultCode = response.getCode();
            resultMessage = response.getSubCode();
        } catch (AlipayApiException e) {
            logger.error("[AlipayDownloadServiceImpl.getAlipayDownloadBill] __ appId:" + appId , e);
        }

        return resUrl;
    }
}
